#!/usr/bin/env python

"""
This module provides all the functionnalities to setu/access database where is
stored information about the contest.
"""

from climber import Climber
from slope import Slope
from contest import Contest
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import mapper
from sqlalchemy.orm import sessionmaker

import os

DEFAULT_DB_NAME='contest.db'

class Database:
    def __init__(self, db_name=DEFAULT_DB_NAME, echo=False):
        self.db_path = os.path.abspath(db_name)
        print self.db_path
        engine = create_engine('sqlite:///%s' % self.db_path, echo=echo)
        
        metadata = MetaData()
        climbers_table = Table('climbers', metadata,
                            Column('id', Integer, primary_key=True),
                            Column('name', String(40)),
                            Column('fullname', String(100)),
                            Column('age', Integer),
                            Column('sexe', String(6)),
                            Column('category', String(15))
                            )
        
        metadata.create_all(engine)
        mapper(Climber, climbers_table)
        
        Session = sessionmaker(bind=engine, autoflush=True, transactional=True)
        self.session = Session()
        
    def save(self):
        try:
            self.session.commit()
        except sqlalchemy.exceptions.IntegrityError:
            pass
        
    def add_climber(self, climber):    
        for object in self.session.query(Climber):
            if climber.id == object.id:
                return
        self.session.save(climber)
        self.save()
        
    def add(self, object):
        if isinstance(object, Climber):
            self.add_climber(object)
        
if __name__ == '__main__':
        db = Database()
        db.add(Climber('Prenom', 'Nom de Famille', 1))
        for climber in db.session.query(Climber):
            print climber.fullname
        